const axios = require('axios');

class AccountAPIRegistry {
  constructor(storage = null) {
    // API端点配置 - 根据接口文档更新
    this.apiConfig = {
      baseURL: 'http://172.19.15.2:3000', // 根据接口文档更新服务器地址
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    };

    // API路径映射 - 根据接口文档更新
    this.apiPaths = {
      login: '/auth/login',
      register: '/auth/register',
      bindThirdParty: '/auth/code',
      unbindThirdParty: '/auth/unbind',
      getBindings: '/auth/bindings',
      refreshToken: '/auth/refresh-jwt',
      getAuthorizationCode: '/auth/getAuthorizationCode'
    };

    // 存储实例，用于获取token
    this.storage = storage;

    // 创建axios实例
    this.client = axios.create(this.apiConfig);

    // 添加请求拦截器
    this.client.interceptors.request.use(config => {
      // 从存储获取token
      if (this.storage) {
        const token = this.storage.getToken();
        if (token) {
          config.headers['Authorization'] = `Bearer ${token}`;
        }
      }
      return config;
    }, error => {
      return Promise.reject(error);
    });

    // 添加响应拦截器处理token过期
    this.client.interceptors.response.use(
      response => response,
      async error => {
        if (error.response?.status === 401 && this.storage) {
          // token过期，尝试刷新
          const refreshToken = this.storage.getRefreshToken();
          if (refreshToken) {
            try {
              const refreshResponse = await this.refreshAccessToken(refreshToken);
              if (refreshResponse.success) {
                // 重新发送原请求
                error.config.headers['Authorization'] = `Bearer ${refreshResponse.data.token}`;
                return this.client.request(error.config);
              }
            } catch (refreshError) {
              console.error('Token刷新失败:', refreshError);
            }
          }
        }
        return Promise.reject(error);
      }
    );
  }

  // 设置存储实例
  setStorage(storage) {
    this.storage = storage;
  }

  // 调用API
  async callAPI(apiName, data) {
    if (!this.apiPaths[apiName]) {
      throw new Error(`未知的API: ${apiName}`);
    }

    try {
      const response = await this.client.post(this.apiPaths[apiName], data);
      return response.data;
    } catch (error) {
      console.error(`API调用错误 (${apiName}):`, error);

      // 处理错误响应
      if (error.response) {
        // 服务器返回了错误响应
        return {
          success: false,
          message: error.response.data.message || `${apiName}请求失败`,
          status: error.response.status,
          errors: error.response.data.errors
        };
      } else if (error.request) {
        // 请求已发送但没有收到响应
        return {
          success: false,
          message: '服务器无响应'
        };
      } else {
        // 请求设置时发生错误
        return {
          success: false,
          message: error.message
        };
      }
    }
  }

  // GET请求方法
  async callAPIGet(apiName, params = {}) {
    if (!this.apiPaths[apiName]) {
      throw new Error(`未知的API: ${apiName}`);
    }

    try {
      const response = await this.client.get(this.apiPaths[apiName], { params });
      return response.data;
    } catch (error) {
      console.error(`API调用错误 (${apiName}):`, error);

      if (error.response) {
        return {
          success: false,
          message: error.response.data.message || `${apiName}请求失败`,
          status: error.response.status,
          errors: error.response.data.errors
        };
      } else if (error.request) {
        return {
          success: false,
          message: '服务器无响应'
        };
      } else {
        return {
          success: false,
          message: error.message
        };
      }
    }
  }

  // 刷新访问令牌
  async refreshAccessToken(refreshToken) {
    try {
      const response = await this.client.post(this.apiPaths.refreshToken, {
        refreshToken: refreshToken
      });

      if (response.data.status === 'success') {
        // 保存新的token
        if (this.storage) {
          this.storage.saveToken(response.data.data.token);
        }
        return {
          success: true,
          data: response.data.data
        };
      } else {
        return {
          success: false,
          message: response.data.message
        };
      }
    } catch (error) {
      console.error('刷新token失败:', error);
      return {
        success: false,
        message: '刷新token失败'
      };
    }
  }

  // 配置API端点
  configureAPI(apiName, path) {
    if (!apiName || !path) return false;
    this.apiPaths[apiName] = path;
    return true;
  }

  // 设置基础URL
  setBaseURL(url) {
    if (!url) return false;
    this.apiConfig.baseURL = url;
    this.client = axios.create(this.apiConfig);
    return true;
  }
}

module.exports = AccountAPIRegistry;
